package lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
使用可重入锁实现线程间的通信
 */
//第一步创建资源类，定义属性和操作方法
class share{

  private int number = 1;

  private Lock lock = new ReentrantLock();

  Condition condition = lock.newCondition();

//  +1
  public void incr() throws InterruptedException {

//    上锁
    lock.lock();

    try {
//    判断
      while(number !=0){
        condition.await();
      }
//    干活
      number++;
      System.out.println(Thread.currentThread().getName() + "::" + number);
//    通知
      condition.signalAll();
    }finally {
      lock.unlock();
    }


  }

//  -1
  public void decr() throws InterruptedException {
    lock.lock();

    try {
      while (number !=1){
        condition.await();
      }
      number--;
      System.out.println(Thread.currentThread().getName() + "::" + number);
      condition.signalAll();
    }finally {
      lock.unlock();
    }

  }

}

//第三步，创建多线程
public class ThreadDemo2 {

  public static void main(String[] args) {

    share share = new share();

    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i = 0; i < 10;i++){
          try {
            share.incr();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    },"AA").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i = 0; i < 10;i++){
          try {
            share.decr();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    },"BB").start();

  }
}
